package cn.wolfcode.trip.app.controller;

import cn.wolfcode.trip.app.util.UserContext;
import cn.wolfcode.trip.base.domain.Question;
import cn.wolfcode.trip.base.domain.QuestionComment;
import cn.wolfcode.trip.base.domain.QuestionCommentReply;
import cn.wolfcode.trip.base.query.QueryObject;
import cn.wolfcode.trip.base.query.QuestionCommentQueryObject;
import cn.wolfcode.trip.base.service.IQuestionService;
import cn.wolfcode.trip.base.util.JSONResult;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("questions")
public class QuestionController {
    @Autowired
    private IQuestionService questionService;
    //查询问题及作者
    @GetMapping
    public Map list(QueryObject qo){
        qo.setOrderBy("q.createTime desc");
        PageInfo pageInfo = questionService.query(qo);
        HashMap<String, Object> map = new HashMap<>();
        map.put("pageInfo",pageInfo);
        map.put("keyword",qo.getKeyword());
        return map;
    }
    //根据问题的id查询问题
    @GetMapping("/{id}")
    public Question getById(@PathVariable Long id){
        return questionService.getById(id);
    }
    //查询所有的评论,分页
    @GetMapping("/{questionId}/comments")
    public PageInfo getCommentsByQuestionId(QuestionCommentQueryObject qo){
        qo.setOrderBy("qc.createTime desc");
        return questionService.getCommentsByQuestionId(qo);
    }
    //新增某个问题的评论
    @PostMapping("/{questionId}/comments")
    public JSONResult save(QuestionComment questionComment){
        questionComment.setUser(UserContext.getCurrentUser());
        questionService.save(questionComment);
        return new JSONResult();
    }
    //新增一个问题
    @PostMapping
    public JSONResult save(Question question){
        question.setUser(UserContext.getCurrentUser());
        questionService.save(question);
        return new JSONResult();
    }
    //更新浏览量,回答量
    @PutMapping("/{id}")
    public JSONResult updateNum(Question question){
        questionService.updateNum(question);
        return new JSONResult();
    }
    //新增评论的回复
    @PostMapping("/comments/{commentId}")
    public JSONResult saveReply(QuestionCommentReply commentReply){
        commentReply.setUser(UserContext.getCurrentUser());
        questionService.saveReply(commentReply);
        return new JSONResult();
    }
}
